// miniprogram/pages/admin/order/newOrder/newOrder.js
const app = getApp();
const util = require("../../../utils/util");
Page({

  rules: {
    customer: 'require',
    service: 'require'
  },
  /**
   * 页面的初始数据
   */
  data: {
    pr: {
      // customer: {
      //   // name: '请选择'
      // },
      // service: {
      //   // title: '请选择',
      //   // coupon: {
      //   //   desc: '50元/张',
      //   //   couponType: 0,
      //   //   price: 50,
      //   //   amount: 10,
      //   //   bonus: 1
      //   // }
      // },

    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const that = this;
    app.login(user => {
      if (!user.studioid) {
        wx.navigateBack();
        return;
      }
      wx.cloud.callFunction({
        name: 'crud',
        data: {
          op: 'get',
          table: 'service',
          where: {
            studioid: user.studioid
          },
          field: {
            title: true,
            price: true,
            deposit: true,
            hours: true,
            film: true,
            album: true,
            coupon: true,
            fixCoupon: true,
            'cover.src': true,
            filmGive: true,
            albumGive: true,
            category: true,
            isLimit: true,
            timeLimit: true
          }
        },
        success: res => {
          let serviceList = res.result.data;
          serviceList.map((v, i) => {
            v.desc = `${v.isLimit  || v.timeLimit ?'【促销】':''}${v.title}（${v.price}元）`
          })
          that.setData({
            serviceList
          });
        }
      })
      if (options._id) {
        wx.cloud.callFunction({
          name: 'crud',
          data: {
            op: 'get',
            table: 'order',
            where: {
              _id: options._id,
              studioid: user.studioid
            }
          },
          success: res => {
            if (res.result.data.length > 0) {
              let order = res.result.data[0]
              order.haspaid = order.payments.filter(item => item.time).length > 0 ? true : false
              that.setData({
                pr: order
              });
              if (res.result.data[0].status == 0) {
                wx.setNavigationBarTitle({
                  title: '确认订单'
                })
              } else {
                wx.setNavigationBarTitle({
                  title: '修改订单'
                })
              }

            }
          }
        })
      }
    });
  },

  setCoupon: function (e) {
    const that = this;
    let fixCoupon = e.currentTarget.dataset.index == 'fixCoupon';
    let coupon = fixCoupon ? this.data.pr.service.fixCoupon : this.data.pr.service.coupon;
    if (!coupon) {
      coupon = this.data.pr.service.coupon;
    }
    wx.navigateTo({
      url: '../../chooseMorePolicy/chooseMorePolicy',
      events: {
        setCoupon: res => {
          console.log("result", res);
          if (fixCoupon) {
            that.setData({
              'pr.service.fixCoupon': res.coupon
            });
          } else {
            that.setData({
              'pr.service.coupon': res.coupon
            });
          }
        }
      },
      success: res => {
        res.eventChannel.emit('setCoupon', {
          coupon: coupon
        })
      }
    })
  },

  serviceChange: function (e) {
    let index = e.detail.value;
    let service = this.data.serviceList[index];

    let pr = this.data.pr;
    pr.serviceIndex = index;
    pr.service = service;

    pr.price = parseInt(service.price);
    //  pr.film = service.film;
    //  pr.coupon = service.coupon;
    //  pr.album = service.album;
    pr.deposit = service.deposit;
    //  pr.albumGive = service.albumGive;
    //  pr.filmGive = service.filmGive;
    this.setData({
      pr: pr
    });
  },

  /**
   * 保存数据
   */
  submitData: function (order) {
    wx.showLoading({
      title: '正在保存数据'
    });
    wx.cloud.callFunction({
      name: 'crud',
      data: {
        table: 'order',
        op: 'update',
        data: order
      },
      success: res => {
        wx.hideLoading();
        console.debug("Update result", res.result);
        let pages = getCurrentPages();
        if (res.result._id || res.result.stats.updated) {
          if (pages.length > 1) {
            pages[pages.length - 2].onLoad(pages[pages.length - 2].options);
          }
          wx.navigateBack();
        }
      },
      fail: err => {
        console.log(err);
        wx.hideLoading();
        wx.showToast({
          title: err.errMsg,
          icon: 'none'
        })
      }
    })
  },

  apply: function (e) {
    let order = this.data.pr;
    for (var n in e.detail.value) {
      let nn = n.split('.');
      if (nn.length == 1) {
        order[n] = e.detail.value[n]
      } else {
        if (!order[nn[0]]){
          order[nn[0]] = {};
        }
        order[nn[0]][nn[1]] = e.detail.value[n];
      }
    }

    order.price = parseInt(order.price);
    order.deposit = parseInt(order.deposit);

    if (!order.haspaid) {
      order.payments = [{
          'title': '定金',
          'amount': parseInt(order.deposit)
        },
        {
          'title': '尾款',
          'amount': parseInt(order.price) - parseInt(order.deposit)
        }
      ]
    }

    let checkResult = util.checkForm(order, this.rules);
    this.setData({
      errinfo: checkResult
    })
    if (Object.keys(checkResult).length != 0) {
      return;
    }

    if (!order._id||order.status==0) {
      order.status = 1;
      if (app.globalData.user.studioid) {
        order.studioid = app.globalData.user.studioid;
      } else {
        wx.showModal({
          title: '提示',
          content: '您没有对应工作室，请创建或由主账号邀请加入',
          showCancel: false,
          success: r => {
            if (r.confirm) {
              wx.navigateTo({
                url: '../../studio/studio'
              })
            }
          }
        })
        return;
      }
      order.visit = 0;
      order.sales = 0;
      order.logs = [{
        time: util.formatTime(new Date()),
        user: app.globalData.user.name,
        text: '创建订单'
      }]
      // order.submittime = util.formatTime(new Date());
    } else {
      if (!order.logs) order.logs = [];
      order.logs.push({
        time: util.formatTime(new Date()),
        user: app.globalData.user.name,
        text: '修改订单'
      })
    }

    // order.updatetime = util.formatTime(new Date());
    this.submitData(order);
  },

  switchChange: function (e) {
    if (e.target.id) {
      this.setData({
        [`pr.${e.target.id}`]: e.detail.value
      });
    } else {
      console.error("控件没有设置 id!")
    }
  },

  selectCustomer: function (e) {
    const that = this;
    wx.navigateTo({
      url: '../../customer/selectCustomer/selectCustomer',
      events: {
        setCustomer: res => {
          console.log("result", res);
          that.setData({
            ['pr.customer']: res.customer
          });
        }
      },
      success: res => {
        res.eventChannel.emit('setCustomer', {
          customer: this.data.pr.customer
        })
      }
    })
  },
  requestSubscribeMessage(e) {
    app.requestOrderSubscribeMessage()
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})